import crypto from 'crypto';
import userModel from '../models/User';
import { returnResult } from '../utils/response/returnResult';
export default new class userService {

    /**
     * 
     * @param val {name:用户名,password:密码}
     * @returns 
     */
    public async login(email: string, password: string) {
        // if (!email) throw returnResult.error('邮箱不能为空');
        // if (!password) throw returnResult.error('密码不能为空');
        const pas = crypto.createHash('md5').update(password + '').digest("hex");
        const res = await userModel.findOne({ email, password: pas });
        if (res === null) throw returnResult.error('邮箱或密码错误');
        return res;
    }
    /**
     * 创建用户
     * @param val {interface User}
     * @returns 
     */
    public async create(val: any) {
        const user = new userModel(val);
        const error = user.validateSync();
        const find = await userModel.findOne({ email: val.email });
        if (find !== null) throw returnResult.error('该邮箱已被占用');
        if (error) throw returnResult.error(error.message);
        user.password = crypto.createHash('md5').update(user.password).digest("hex");
        return await user.save(val);
    }
    /**
     * 根据_id查找用户
     * @param val {interface User}
     * @returns 
     */
    public async findById(val: string) {
        return await userModel.findById(val);
    }
}; 